Skip to content

feat(web): validation of the token address for ERC20/721/1155 types #2052

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 7 commits into
base: dev
Choose a base branch
from

Conversation

jaybuidl
Copy link
Member

@jaybuidl jaybuidl commented Jul 22, 2025

PR-Codex overview

This PR enhances the token validation functionality in the dispute management system. It introduces checks for ERC20, ERC721, and ERC1155 tokens, updating the context and UI to reflect the validation status of token gates in gated dispute kits.

Detailed summary

  • Added isTokenGateValid property to NewDisputeContext.
  • Updated extraDataToTokenInfo to return undefined for non-gated dispute kits.
  • Enhanced NextButton to include gated token validation logic.
  • Implemented hooks useERC20ERC721Validation and useERC1155Validation for token address validation.
  • Updated Court component to manage token validation state and UI feedback.
  • Styled components for validation feedback in the Court component.

✨ Ask PR-Codex anything about this PR by commenting with /codex {your question}

Summary by CodeRabbit

  • New Features

    • Added real-time validation for Ethereum token contract addresses (ERC-20, ERC-721, ERC-1155) when configuring gated dispute kits.
    • Visual feedback is now provided for token address validation, including loading, valid, and invalid states.
    • The "Next" button is now disabled if the token address for a gated dispute kit is invalid.
    • Introduced a tri-state validation status for token gating: not validated, valid, and invalid.
  • Bug Fixes

    • Validation state is reset appropriately when the token address or type changes.

@jaybuidl jaybuidl requested a review from a team as a code owner July 22, 2025 23:56
Copy link
Contributor

coderabbitai bot commented Jul 22, 2025

Walkthrough

Adds token-gate address validation for gated dispute kits: new validation hooks, UI feedback in the Court page, state synchronization into dispute context, Next button gating logic, and a small API change to extraDataToTokenInfo and IGatedDisputeData to carry validation state.

Changes

Cohort / File(s) Change Summary
Token validation hooks
web/src/hooks/useTokenAddressValidation.ts
New hooks to validate ERC-20/ERC-721 and ERC-1155 token addresses (debounce, contract call to balanceOf, caching, error messages). Exports useERC20ERC721Validation and useERC1155Validation.
Gated dispute data interface
web/src/context/NewDisputeContext.tsx
Added optional `isTokenGateValid?: boolean
Court page (validation + UI)
web/src/pages/Resolver/Parameters/Court.tsx
Integrates validation hooks, adds validation UI (spinner, icons, messages, input styling), syncs isTokenGateValid into context, resets validation on input/type change.
Navigation gating
web/src/pages/Resolver/NavigationButtons/NextButton.tsx
Consumes isTokenGateValid and updates route enable/disable logic for /resolver/court alongside disputeKit checks.
Extra data parsing API
web/src/utils/extradataToTokenInfo.ts
Changed return type to `GatedTokenInfo

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CourtPage
    participant ValidationHook
    participant EthereumClient
    participant DisputeContext
    participant NextButton

    User->>CourtPage: Enter token address / toggle ERC-1155
    CourtPage->>ValidationHook: Request validation (address, type)
    ValidationHook->>EthereumClient: Call contract balanceOf / check interface
    EthereumClient-->>ValidationHook: Respond (success / revert / error)
    ValidationHook-->>CourtPage: Return isValid / error / loading
    CourtPage->>DisputeContext: Update isTokenGateValid (null/true/false)
    CourtPage-->>User: Show spinner / check / cross and message
    NextButton->>DisputeContext: Read isTokenGateValid + disputeKitId
    NextButton-->>User: Enable or disable navigation
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Possibly related PRs

Suggested reviewers

  • jaybuidl
  • alcercu
  • kemuru

Poem

"A rabbit found a token gate,
I sniffed the address — is it great?
I spin my wheel and give a sign,
A green hop in or red decline.
🐇🔎✨"

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/gated-dk-address-validation

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai or @coderabbitai title anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@jaybuidl jaybuidl requested review from tractorss and kemuru and removed request for a team July 22, 2025 23:56
@jaybuidl jaybuidl force-pushed the feat/gated-dk-address-validation branch from 8a3862f to f1fe7c9 Compare July 23, 2025 13:58
Base automatically changed from web/dk-support-improvement to dev July 28, 2025 15:54
Copy link

netlify bot commented Aug 5, 2025

Deploy Preview for kleros-v2-university failed. Why did it fail? →

Name Link
🔨 Latest commit a374113
🔍 Latest deploy log https://app.netlify.com/projects/kleros-v2-university/deploys/689c61a76ab53a000816bbe4

Copy link

netlify bot commented Aug 5, 2025

Deploy Preview for kleros-v2-testnet ready!

Name Link
🔨 Latest commit a374113
🔍 Latest deploy log https://app.netlify.com/projects/kleros-v2-testnet/deploys/689c61a78d27fe0008c91123
😎 Deploy Preview https://deploy-preview-2052--kleros-v2-testnet.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

Copy link

netlify bot commented Aug 5, 2025

Deploy Preview for kleros-v2-neo ready!

Name Link
🔨 Latest commit a374113
🔍 Latest deploy log https://app.netlify.com/projects/kleros-v2-neo/deploys/689c61a7b173930008e51126
😎 Deploy Preview https://deploy-preview-2052--kleros-v2-neo.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

Copy link

netlify bot commented Aug 5, 2025

Deploy Preview for kleros-v2-testnet-devtools ready!

Name Link
🔨 Latest commit a374113
🔍 Latest deploy log https://app.netlify.com/projects/kleros-v2-testnet-devtools/deploys/689c61a7e3c5ff00086b2b57
😎 Deploy Preview https://deploy-preview-2052--kleros-v2-testnet-devtools.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (3)
web/src/pages/Resolver/NavigationButtons/NextButton.tsx (1)

24-25: Consider using optional chaining for cleaner code.

-    const gatedData = disputeData.disputeKitData as IGatedDisputeData;
-    if (!gatedData?.tokenGate?.trim()) return true; // No token address provided, so valid
+    const gatedData = disputeData.disputeKitData as IGatedDisputeData;
+    if (!gatedData.tokenGate?.trim()) return true; // No token address provided, so valid
web/src/hooks/useTokenAddressValidation.ts (2)

169-171: Consider preserving error details for debugging.

The catch block discards the original error which might contain useful information for debugging contract-specific issues.

-      } catch {
-        throw new Error(`Address does not implement ${tokenType} interface`);
+      } catch (error) {
+        console.debug(`Token validation failed for ${debouncedAddress}:`, error);
+        throw new Error(`Address does not implement ${tokenType} interface`);
       }

202-210: Error message handling could be more robust.

The error message parsing relies on string matching which might be fragile if error messages change.

Consider using error codes or more structured error handling if the contract interaction library supports it.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e3ed3c9 and 92852da.

📒 Files selected for processing (4)
  • web/src/context/NewDisputeContext.tsx (1 hunks)
  • web/src/hooks/useTokenAddressValidation.ts (1 hunks)
  • web/src/pages/Resolver/NavigationButtons/NextButton.tsx (3 hunks)
  • web/src/pages/Resolver/Parameters/Court.tsx (6 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (14)
  • GitHub Check: Redirect rules - kleros-v2-neo
  • GitHub Check: Header rules - kleros-v2-neo
  • GitHub Check: Redirect rules - kleros-v2-testnet
  • GitHub Check: Pages changed - kleros-v2-neo
  • GitHub Check: Header rules - kleros-v2-testnet
  • GitHub Check: Redirect rules - kleros-v2-university
  • GitHub Check: Redirect rules - kleros-v2-testnet
  • GitHub Check: Pages changed - kleros-v2-testnet
  • GitHub Check: Header rules - kleros-v2-university
  • GitHub Check: Header rules - kleros-v2-testnet
  • GitHub Check: Pages changed - kleros-v2-testnet
  • GitHub Check: Pages changed - kleros-v2-university
  • GitHub Check: Analyze (javascript)
  • GitHub Check: contracts-testing
🔇 Additional comments (7)
web/src/context/NewDisputeContext.tsx (1)

64-64: LGTM! Well-designed validation state property.

The tri-state boolean (null = not validated, false = invalid, true = valid) is an appropriate design choice for tracking asynchronous validation status.

web/src/pages/Resolver/NavigationButtons/NextButton.tsx (1)

20-29: LGTM! Validation logic is well-structured.

The memoized validation check correctly handles all cases: non-gated kits, empty token addresses, and validated addresses.

web/src/pages/Resolver/Parameters/Court.tsx (3)

1-1: Import statement updated correctly.

Added useEffect import which is used for validation state synchronization.


90-168: Excellent UI feedback components for validation.

The styled components provide clear visual feedback with loading spinner, success checkmark, and error cross. The color scheme follows standard UX patterns (green for success, red for error).


327-336: Well-implemented validation feedback UI.

The conditional rendering of validation status with appropriate messages for each state (validating, error, success) provides excellent user experience.

web/src/hooks/useTokenAddressValidation.ts (2)

122-129: Good implementation of debouncing.

The 500ms debounce delay is appropriate for reducing unnecessary network calls while maintaining responsive UX.


150-152: Appropriate caching and retry configuration.

The 5-minute cache time and single retry with 1-second delay provide a good balance between performance and user experience.

Copy link
Contributor

@tractorss tractorss left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks good, pushed some small refactors

jaybuidl and others added 2 commits August 6, 2025 00:47
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
coderabbitai[bot]
coderabbitai bot previously approved these changes Aug 6, 2025
Copy link

Quality Gate Failed Quality Gate failed

Failed conditions
C Reliability Rating on New Code (required ≥ A)

See analysis details on SonarQube Cloud

Catch issues before they fail your Quality Gate with our IDE extension SonarQube for IDE

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🔭 Outside diff range comments (1)
web/src/utils/extradataToTokenInfo.ts (1)

24-29: Avoid Buffer in the browser; use viem’s bytesToHex

Using Buffer can break in web builds if polyfills aren’t present. viem exposes bytesToHex which is portable and simpler.

Apply these changes:

-import { Address, hexToBytes } from "viem";
+import { Address, hexToBytes, bytesToHex } from "viem";
@@
-  const packed = BigInt("0x" + Buffer.from(packedBytes).toString("hex"));
+  const packed = BigInt(bytesToHex(packedBytes));
@@
-  const tokenId = BigInt("0x" + Buffer.from(tokenIdBytes).toString("hex"));
+  const tokenId = BigInt(bytesToHex(tokenIdBytes));
♻️ Duplicate comments (1)
web/src/pages/Resolver/NavigationButtons/NextButton.tsx (1)

44-45: Court step gating is correct and enforces mandatory token address for gated kits

Disabling Next when the token gate is missing/invalid, courtId is unset, or disputeKitId is missing aligns with the requirement that token address is mandatory for token-gated dispute kits.

🧹 Nitpick comments (3)
web/src/utils/extradataToTokenInfo.ts (1)

19-20: Be explicit: return undefined instead of bare return

Returning undefined explicitly improves readability and satisfies stricter linters (e.g., consistent-return).

-  if (extraDataBytes.length < 160) {
-    return;
-  }
+  if (extraDataBytes.length < 160) {
+    return undefined;
+  }
web/src/pages/Resolver/NavigationButtons/NextButton.tsx (2)

20-30: Simplify and de-stale: compute gating validity without useMemo and remove unnecessary type assertion

The computation is trivial and better evaluated directly each render. This avoids potential staleness if the context mutates the object in place and removes an unnecessary cast (type is already narrowed by the "type" discriminator).

-  // Check gated dispute kit validation status
-  const isGatedTokenValid = React.useMemo(() => {
-    if (!disputeData.disputeKitData || disputeData.disputeKitData.type !== "gated") return true;
-
-    const gatedData = disputeData.disputeKitData as IGatedDisputeData;
-    if (!gatedData?.tokenGate?.trim()) return false; // No token address provided, so invalid
-
-    // If token address is provided, it must be validated as valid ERC20
-    return gatedData.isTokenGateValid === true;
-  }, [disputeData.disputeKitData]);
+  // Check gated dispute kit validation status
+  const isGatedTokenValid =
+    disputeData.disputeKitData?.type !== "gated"
+      ? true
+      : Boolean(disputeData.disputeKitData.tokenGate?.trim()) &&
+        disputeData.disputeKitData.isTokenGateValid === true;

Optional (if ERC-1155 requires a tokenId to proceed): additionally gate on tokenId presence for ERC-1155:

-      : Boolean(disputeData.disputeKitData.tokenGate?.trim()) &&
-        disputeData.disputeKitData.isTokenGateValid === true;
+      : Boolean(disputeData.disputeKitData.tokenGate?.trim()) &&
+        disputeData.disputeKitData.isTokenGateValid === true &&
+        (!disputeData.disputeKitData.isERC1155 ||
+          String(disputeData.disputeKitData.tokenId ?? "").trim() !== "");

24-26: Remove the type assertion; discriminated union already narrows

After checking type !== "gated", TS can narrow disputeKitData to IGatedDisputeData when type === "gated", making the cast redundant.

No separate diff needed if you apply the simplification in the previous comment; otherwise:

-    const gatedData = disputeData.disputeKitData as IGatedDisputeData;
+    const gatedData = disputeData.disputeKitData;
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d78e212 and a374113.

📒 Files selected for processing (2)
  • web/src/pages/Resolver/NavigationButtons/NextButton.tsx (3 hunks)
  • web/src/utils/extradataToTokenInfo.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (3)
📚 Learning: 2025-05-15T06:50:40.859Z
Learnt from: tractorss
PR: kleros/kleros-v2#1982
File: web/src/pages/Resolver/Landing/index.tsx:62-62
Timestamp: 2025-05-15T06:50:40.859Z
Learning: In the Landing component, it's safe to pass `dispute?.dispute?.arbitrated.id as 0x${string}` to `usePopulatedDisputeData` without additional null checks because the hook internally handles undefined parameters through its `isEnabled` flag and won't execute the query unless all required data is available.

Applied to files:

  • web/src/pages/Resolver/NavigationButtons/NextButton.tsx
📚 Learning: 2024-10-14T13:58:25.708Z
Learnt from: Harman-singh-waraich
PR: kleros/kleros-v2#1703
File: web/src/hooks/queries/usePopulatedDisputeData.ts:58-61
Timestamp: 2024-10-14T13:58:25.708Z
Learning: In `web/src/hooks/queries/usePopulatedDisputeData.ts`, the query and subsequent logic only execute when `disputeData.dispute?.arbitrableChainId` and `disputeData.dispute?.externalDisputeId` are defined, so `initialContext` properties based on these values are safe to use without additional null checks.

Applied to files:

  • web/src/pages/Resolver/NavigationButtons/NextButton.tsx
📚 Learning: 2024-10-29T10:13:04.524Z
Learnt from: Harman-singh-waraich
PR: kleros/kleros-v2#1729
File: web/src/layout/Header/navbar/Menu/Settings/Notifications/FormContactDetails/index.tsx:69-69
Timestamp: 2024-10-29T10:13:04.524Z
Learning: In `web/src/layout/Header/navbar/Menu/Settings/Notifications/FormContactDetails/index.tsx`, when the button is disabled, the associated logic won't be reached, and certain code paths may exist for TypeScript purposes.

Applied to files:

  • web/src/pages/Resolver/NavigationButtons/NextButton.tsx
🧬 Code Graph Analysis (1)
web/src/pages/Resolver/NavigationButtons/NextButton.tsx (1)
web/src/context/NewDisputeContext.tsx (1)
  • IGatedDisputeData (59-65)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: Redirect rules - kleros-v2-testnet
  • GitHub Check: Header rules - kleros-v2-testnet
  • GitHub Check: Pages changed - kleros-v2-testnet
🔇 Additional comments (2)
web/src/utils/extradataToTokenInfo.ts (1)

13-16: ```diff

  • Public API now returns undefined — verify all call sites handle it
  • Verify callers of extraDataToTokenInfo handle undefined result

Findings: Only one usage in web/src/pages/Resolver/Landing/index.tsx – inside a useMemo:

const gatedTokenInfo = useMemo(() => {
  if (isUndefined(extradata)) return
  return extraDataToTokenInfo(extradata)
}, [roundData])
  • The code guards only against a missing extradata input, not against the function returning undefined when the data isn’t a gated disputeKit.
  • In practice, both “no input” and “non-gated data” yield undefined here, so downstream code sees the same value.
  • Confirm that wherever gatedTokenInfo gets used, the component tolerates it being undefined (e.g. via conditional rendering or optional chaining).

Action items:
• In web/src/pages/Resolver/Landing/index.tsx, audit any usage of gatedTokenInfo to ensure you check for undefined before accessing its properties.
• If additional call sites of extraDataToTokenInfo exist elsewhere in the codebase, repeat this check.

web/src/pages/Resolver/NavigationButtons/NextButton.tsx (1)

7-8: LGTM on importing IGatedDisputeData for accurate narrowing

Importing the discriminated union member improves type safety across components relying on disputeKitData.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants